<template>
  <div class="ml-[-20px] p-[20px] FreightDetailTable">
    <div class="mb-[20px]">
      <a-button type="primary" class="mr-[20px]" @click="addAddress">添加计费区间</a-button>

      <a-button type="primary" @click="allDel">批量删除</a-button>
    </div>
    <BasicTable @register="registerTable" @selection-change="selectionChange">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction stopButtonPropagation :actions="createActions(record)" />
        </template>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts" setup>
  import { message } from 'ant-design-vue';
  // import { watch } from 'vue';
  import { BasicTable, useTable, TableAction, ActionItem, EditRecordRow } from '@/components/Table';
  import {
    addFreightInfo,
    getFreightDetail,
    updateFreightDetail,
    deleteByBatchDelete,
  } from '@/api/eslogis-tps/index';
  import { onMounted, ref } from 'vue';

  // 获取外部传入的数据
  const { detailInfo } = defineProps({
    detailInfo: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  console.log('🚀 ~ detailInfo:', detailInfo);

  const columns = [
    {
      title: '最小重量(吨)',
      dataIndex: 'leastWeight',
      editRow: true,
    },
    {
      title: '最大重量(吨)',
      dataIndex: 'maxWeight',
      editRow: true,
    },
    {
      title: '提货费(固定价)(元)',
      dataIndex: 'fixedPrice',
      editRow: true,
    },
    {
      title: '提货费(吨单价)(元)',
      dataIndex: 'tonPrice',
      editRow: true,
    },
    {
      title: '运输费(元)',
      dataIndex: 'transportPrice',
      editRow: true,
    },
    {
      title: '送货费(元)',
      dataIndex: 'deliverPrice',
      editRow: true,
    },
    {
      title: '包车价(元)',
      dataIndex: 'charteredPrice',
      editRow: true,
    },
    {
      width: 160,
      title: '操作',
      dataIndex: 'action',
    },
  ];

  const [
    registerTable,
    { reload, getDataSource, setTableData, insertTableDataRecord, getPaginationRef },
  ] = useTable({
    columns: columns,
    showIndexColumn: false,
    immediate: false,
    canResize: false,
    isCanResizeParent: true,
    pagination: true,
    showTableSetting: true,
    showSelectionBar: true, // 显示多选状态栏
    rowSelection: {
      type: 'checkbox',
    },
    api: getFreightDetail,
    beforeFetch: (params) => {
      return {
        ...params,
        ...detailInfo,
      };
    },
    // afterFetch: (res) => {
    //   return res.map((item) => {
    //     return {
    //       ...item,
    //       id: id.value,
    //       origin: item.originProvince + item.originCity + (item.originCounty || ''),
    //       dest: item.destProvince + item.destCity + (item.destCounty || ''),
    //     };
    //   });
    // },
  });

  const selectLists = ref([]);

  const selectionChange = ({ rows }) => {
    console.log('🚀 ~ change ~ e,e1:', rows);
    selectLists.value = rows.map((i) => {
      return i.id;
    });
  };

  const allDel = async () => {
    const res = getPaginationRef();
    console.log('🚀 ~ allDel ~ res:', res);

    if (selectLists.value.length >= res.total) {
      message.error('至少保留一条计费区间');
      return;
    } else if (selectLists.value.length === 0) {
      message.error('请选择一条计费区间');
      return;
    }

    try {
      await deleteByBatchDelete(selectLists.value);
      message.success('删除成功');
      reload();
    } catch (err) {
      console.log('🚀 ~ allDel ~ err:', err);
    }
  };

  // 新增地址
  const addAddress = () => {
    insertTableDataRecord({
      leastWeight: '',
      maxWeight: '',
      fixedPrice: '',
      tonPrice: '',
      transportPrice: '',
      deliverPrice: '',
      charteredPrice: '',
      editable: true,
    });
  };

  function createActions(record: EditRecordRow): ActionItem[] {
    if (!record.editable) {
      return [
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
        },
        {
          label: '删除',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleDelete.bind(null, record),
          },
        },
      ];
    }
    return [
      {
        label: '保存',
        onClick: handleRowSave.bind(null, record),
      },
      {
        label: '取消',
        popConfirm: {
          title: '是否取消编辑',
          confirm: handleCancel.bind(null, record),
        },
      },
    ];
  }

  async function handleEdit(record: EditRecordRow) {
    record.onEdit?.(true);
  }

  async function handleDelete(record: Recordable) {
    const data = getDataSource();
    if (data.length <= 1) {
      message.error('至少保留一条计费区间');
      return;
    }
    const index = data.findIndex((item) => item.key === record.key);
    data.splice(index, 1);
    try {
      await deleteByBatchDelete([record.id]);
      message.success('删除成功');
      reload();
    } catch (err) {
      console.log('🚀 ~ handleDelete ~ err:', err);
    }
  }

  function handleCancel(record: EditRecordRow) {
    if (!record.id) {
      const data = getDataSource();
      const index = data.findIndex((item) => item.key === record.key);
      data.splice(index, 1);
    }
    record.onEdit?.(false, false);
  }

  async function handleRowSave(record: EditRecordRow) {
    if (record.leastWeight > record.maxWeight) {
      message.error('最小重量不可大于最大重量');
      return;
    }

    if (record.leastWeight <= 0) {
      message.error('最小重量不可小于0');
      return;
    }

    if (record.maxWeight <= 0) {
      message.error('最大重量不可小于0');
      return;
    }

    if (record.fixedPrice <= 0) {
      message.error('提货费(固定价)不可小于0');
      return;
    }

    if (record.tonPrice <= 0) {
      message.error('提货费(吨单价)不可小于0');
      return;
    }

    if (record.transportPrice <= 0) {
      message.error('运输费(元)不可小于0');
      return;
    }

    if (record.deliverPrice <= 0) {
      message.error('送货费(元)不可小于0');
      return;
    }

    if (record.charteredPrice <= 0) {
      message.error('包车价(元)不可小于0');
      return;
    }

    if (record.id) {
      const res = await updateFreightDetail({
        ...detailInfo,
        id: record.id,
        leastWeight: record.leastWeight,
        maxWeight: record.maxWeight,
        fixedPrice: record.fixedPrice,
        tonPrice: record.tonPrice,
        transportPrice: record.transportPrice,
        deliverPrice: record.deliverPrice,
        charteredPrice: record.charteredPrice,
      });
      console.log('🚀 ~ handleEdit ~ res:', res);
      reload();
      record.onEdit?.(false, true);
    } else {
      const res = await addFreightInfo({
        ...detailInfo,
        leastWeight: record.leastWeight,
        maxWeight: record.maxWeight,
        fixedPrice: record.fixedPrice,
        tonPrice: record.tonPrice,
        transportPrice: record.transportPrice,
        deliverPrice: record.deliverPrice,
        charteredPrice: record.charteredPrice,
      });
      console.log('��� ~ handleEdit ~ res:', res);
      record.onEdit?.(false, true);
      reload();
    }
  }

  // async function reloadFun() {
  //   const par = getPaginationRef();
  //   console.log('🚀 ~ reloadFun ~ par:', par);
  //   const data = await getFreightDetail({
  //     ...detailInfo,
  //     size: 10,
  //     current: 1,
  //   });
  //   console.log('🚀 ~ reloadFun ~ data:', data);
  //   setTableData(data.records);
  // }

  onMounted(() => {
    console.log('🚀 ~ onMounted ~ detailInfo:', detailInfo);
    reload();
  });

  defineExpose({
    reload,
    setTableData,
  });
</script>

<style>
  .FreightDetailTable .ant-table {
    margin-block: 0 !important;
    margin-inline: 0 0 !important;
  }
</style>
